import tkinter as tk
from tkinter import messagebox, ttk

from ..core.comparator import DataComparator
from ..models.data_source import CompareConfig, DataSource
from ..utils.logger import logger


class ControlManager(ttk.Frame):
    def __init__(self, master, main_window):
        super().__init__(master)
        self.main_window = main_window
        self._init_control_ui()

    def _init_control_ui(self):
        """初始化控制区域UI"""
        # 左侧控件
        left_frame = ttk.Frame(self)
        left_frame.pack(side=tk.LEFT, fill=tk.X)

        # 开始对比按钮
        ttk.Button(left_frame, text="开始对比", command=self._on_compare).pack(
            side=tk.LEFT, padx=5
        )

        # 显示全部数据选项
        self.show_all_var = tk.BooleanVar(value=False)
        ttk.Checkbutton(
            left_frame,
            text="显示全部数据",
            variable=self.show_all_var,
            command=self._on_show_all_changed,
        ).pack(side=tk.LEFT, padx=5)

        # 列名显示选项
        ttk.Label(left_frame, text="列名显示:").pack(side=tk.LEFT, padx=5)
        self.column_display_var = tk.StringVar(value="数据项名称")
        column_display_combo = ttk.Combobox(
            left_frame,
            textvariable=self.column_display_var,
            values=["数据项名称", "数据项代码"],
            state="readonly",
            width=10,
        )
        column_display_combo.pack(side=tk.LEFT, padx=5)
        column_display_combo.bind(
            "<<ComboboxSelected>>", self._on_column_display_changed
        )

        # 右侧导出按钮
        right_frame = ttk.Frame(self)
        right_frame.pack(side=tk.RIGHT, fill=tk.X)

        # 导出菜单
        self.export_menu = tk.Menu(self, tearoff=0)
        self.export_menu.add_command(
            label="导出为CSV",
            command=lambda: self.main_window._on_export_result(".csv"),
        )
        self.export_menu.add_command(
            label="导出为Excel",
            command=lambda: self.main_window._on_export_result(".xlsx"),
        )
        self.export_menu.add_command(
            label="导出为JSON",
            command=lambda: self.main_window._on_export_result(".json"),
        )

        self.export_button = ttk.Button(
            right_frame, text="导出结果", command=self._show_export_menu
        )
        self.export_button.pack(side=tk.RIGHT, padx=5)

    def _show_export_menu(self):
        """显示导出菜单"""
        x = self.export_button.winfo_rootx()
        y = self.export_button.winfo_rooty() + self.export_button.winfo_height()
        self.export_menu.post(x, y)

    def _on_compare(self):
        """执行数据对比"""
        try:
            # 检查是否有ID字段
            if not self.main_window.id_fields:
                messagebox.showerror("错误", "请至少设置一个ID字段")
                return

            # 获取数据源配置
            source1 = self.main_window._create_data_source(
                self.main_window._find_source_frame("数据源1")
            )
            source2 = self.main_window._create_data_source(
                self.main_window._find_source_frame("数据源2")
            )

            if not source1 or not source2:
                messagebox.showerror("错误", "请先配置数据源")
                return

            # 创建对比配置
            config = CompareConfig(
                fields=self.main_window.data_fields,
                id_fields=self.main_window.id_fields,
                source1=source1,
                source2=source2,
                show_all=self.show_all_var.get(),
            )

            # 执行对比
            comparator = DataComparator(config)
            result_df = comparator.compare()

            # 显示结果
            self.main_window._display_result(result_df)
            logger.info("数据对比完成")

        except Exception as e:
            logger.error(f"数据对比失败: {str(e)}", exc_info=True)
            messagebox.showerror("错误", f"对比失败: {str(e)}")

    def _on_show_all_changed(self):
        """显示选项改变处理"""
        logger.info(f"显示选项改变: {self.show_all_var.get()}")

    def _on_column_display_changed(self, event):
        """列名显示方式改变处理"""
        display_type = (
            "code" if self.column_display_var.get() == "数据项代码" else "name"
        )
        logger.info(f"列名显示方式改变: {display_type}")
        # 通知结果树更新列名显示
        if hasattr(self.main_window, "result_tree"):
            self.main_window.result_tree.update_column_display(display_type)
